using System;
using System.Collections.Specialized;

namespace FreeSwitch.EventSocket.Events
{
	public abstract class Event 
	{
		private int _callingLineNumber;
		private string _name;
		private readonly NameValueCollection _parameters = new NameValueCollection();
		private ILogger _logger = LogManager.GetLogger(typeof (Event));

		public string CoreId { get; set; }
		public DateTime DateLocal { get; set; }
		public DateTime DateGMT { get; set; }

		public string CallingFile { get; set; }

		public string CallingFunction { get; set; }

		public int CallingLineNumber
		{
			get { return _callingLineNumber; }
			set { _callingLineNumber = value; }
		}


		public virtual bool IsChannelEvent
		{
			get { return false; }
		}

		/// <summary>
		/// Gets parameters that has not been parsed.
		/// </summary>
		public NameValueCollection Parameters
		{
			get { return _parameters; }
		}

		public void Parse(NameValueCollection parameters)
		{
			for (int i = 0; i < parameters.Count; ++i)
				ParseCommand(parameters.GetKey(i), parameters.Get(i));
		}


		public virtual bool ParseCommand(string name, string value)
		{
			switch (name)
			{
				case "event-name":
					_name = value;
					break;
				case "core-uuid":
					CoreId = value;
					break;
				case "event-date-local":
					try
					{
						DateLocal = DateTime.Parse(value);
					}
					catch (Exception err)
					{
						_logger.Error("Failed to parse event-date-local: " + value, err);
						Console.WriteLine("event-date-local(" + value + "): " + err);
					}
					break;
				case "event-date-gmt":
					try
					{
						DateGMT = DateTime.Parse(value);
					}
					catch (Exception err)
					{
						_logger.Error("Failed to parse event-date-gmt: " + value, err);
						Console.WriteLine("event-date-gmt(" + value + "): " + err);
					}
					break;
				case "event-calling-file":
					CallingFile = value;
					break;
				case "event-calling-function":
					CallingFunction = value;
					break;
				case "event-calling-line-number":
					int.TryParse(value, out _callingLineNumber);
					break;
				default:
					Parameters.Add(name, value);
					return false;
			}
			return true;
		}

		public virtual void Serialize(ISerializer serializer)
		{
			serializer.Write("Event-Name", _name);
		}

		public override string ToString()
		{
			return "Event(" + _name + ")";
		}
	}
}